package ee.nutilovi.praktikaportaal.tools;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class CryptoTools {
	
	private static String SECRET = "secret";
	
	public static String createSalt() {
		char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
		StringBuilder sb = new StringBuilder();
		Random random = new Random();
		for (int i = 0; i < 20; i++) {
		    char c = chars[random.nextInt(chars.length)];
		    sb.append(c);
		}
		return sb.toString();
	}
	
	public static String hashPassword(String password, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		StringBuffer hash = new StringBuffer();
		MessageDigest md = MessageDigest.getInstance("SHA-256");
		String pwString = password + salt;
		
		md.update(pwString.getBytes("UTF-8"));
		byte[] bytes = md.digest();
		
		for (int i = 0; i < bytes.length; i++) {
    		String hex = Integer.toHexString(0xff & bytes[i]);
   	     	if(hex.length() == 1) hash.append('0');
   	     	hash.append(hex);
		}
		
		return hash.toString() + "|" + salt;
	}
	
	public static String hashUser(String username) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		StringBuffer hash = new StringBuffer();
		MessageDigest md = MessageDigest.getInstance("SHA-256");
		String usernameString = username + SECRET;
		
		md.update(usernameString.getBytes("UTF-8"));
		byte[] bytes = md.digest();

		for (int i = 0; i < bytes.length; i++) {
    		String hex = Integer.toHexString(0xff & bytes[i]);
   	     	if(hex.length() == 1) hash.append('0');
   	     	hash.append(hex);
		}
		
		return hash.toString();
	}
}
